package student

import (
	"XSSS_v2/config"
	"XSSS_v2/handler"
	"XSSS_v2/model"
	"XSSS_v2/pkg/casbin"
	"XSSS_v2/pkg/errno"
	"github.com/gin-gonic/gin"
)

// CreateStu
// @Summary 创建一个学生
// @Tags admin
// @Description Add a student
// @Produce json
// @Param student body model.Student true "stuInfo"
// @Success 200 {object} handler.Response
// @Router /v1/admin [post]
func CreateStu(c *gin.Context) {
	config.Log.Infof("CreateStu request")

	var r CreateRequest
	err := c.Bind(&r)
	if err != nil {
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}
	s := &model.Student{
		Sno:   r.Sno,
		Sname: r.Username,
		Spwd:  r.Password,
	}

	err = s.Validate()
	if err != nil {
		handler.SendResponse(c, errno.ErrValidation, nil)
		return
	}

	err = s.Encrypt()
	if err != nil {
		handler.SendResponse(c, errno.ErrEncrypt, nil)
		return
	}

	err = s.CreateStu()
	if err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	casbin.AddStuUser(s.Sno)

	handler.SendResponse(c, nil, s)

}
